package com.cloud.tsp.service;

import com.cloud.api.domain.service.CertificateRequest;
import com.cloud.core.exception.MyException;
import com.itextpdf.io.font.FontProgram;
import com.itextpdf.io.font.FontProgramFactory;
import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.TextAlignment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * @author 杨斌
 * 2025-03-2025-03-11
 */
@Service
@Slf4j
public class CertificateService {
    public byte[] generatePdf(CertificateRequest request) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try (PdfWriter writer = new PdfWriter(baos);
             PdfDocument pdfDoc = new PdfDocument(writer);
             Document doc = new Document(pdfDoc, PageSize.A4)) {
            // 获取页面尺寸
            float pageWidth = PageSize.A4.getWidth();
            float pageHeight = PageSize.A4.getHeight();
            // 加载模板图片（通过类路径）
            URL templateUrl = CertificateService.class.getClassLoader().getResource("templates/authorization.jpg");
            if (templateUrl == null) {
                throw new MyException("模板文件未找到: templates/authorization.png");
            }
            PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
            canvas.addImageFittedIntoRectangle(ImageDataFactory.create(templateUrl), PageSize.A4, false);

            // 加载 SimSun 字体
            InputStream simsunStream = CertificateService.class.getClassLoader().getResourceAsStream("fonts/SimSunRegular.ttf");
            if (simsunStream == null) {
                throw new MyException("字体文件未找到: fonts/SimSunRegular.ttf");
            }
            // 修复：将 InputStream 转为字节数组
            byte[] simsunBytes = toByteArray(simsunStream);
            FontProgram simsunProgram = FontProgramFactory.createFont(simsunBytes);
            PdfFont simsunFont = PdfFontFactory.createFont(simsunProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);

            // 加载阿里巴巴普惠体
            InputStream alibabaStream = CertificateService.class.getClassLoader().getResourceAsStream("fonts/AlibabaPuHuiTi-2-55-Regular.ttf");
            if (alibabaStream == null) {
                throw new MyException("字体文件未找到: fonts/AlibabaPuHuiTi-2-55-Regular.ttf");
            }
            // 修复：将 InputStream 转为字节数组
            byte[] alibabaBytes = toByteArray(alibabaStream);
            FontProgram alibabaProgram = FontProgramFactory.createFont(alibabaBytes);
            PdfFont alFont = PdfFontFactory.createFont(alibabaProgram, PdfEncodings.IDENTITY_H, PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);

            Paragraph mainP = addParagraph(1.5f, 295, 58, 58);
            mainP.add(addText("兹授权", simsunFont, 18, 0, 0, TextAlignment.LEFT));
            mainP.add(addText(request.getSubjectName(), simsunFont, 18, 1, 1, TextAlignment.LEFT));
            mainP.add(addText("为成功汽车", simsunFont, 18, 0, 0, TextAlignment.LEFT));
            mainP.add(addText(request.getSubjectRegion(), simsunFont, 18, 1, 1, TextAlignment.LEFT));
            mainP.add(addText("区域特约服务站，负责本品牌", simsunFont, 18, 0, 0, TextAlignment.LEFT));
            mainP.add(addText(request.getAuthorizedModels(), simsunFont, 18, 1, 1, TextAlignment.LEFT));
            mainP.add(addText("系列产品在该区域的市场售后服务工作。", simsunFont, 18, 0, 0, TextAlignment.LEFT));
            doc.add(mainP);
            // 加载徽章
            Paragraph mainPa = addParagraph(1.5f, 10, 58, 58);
            URL badgeUrl = CertificateService.class.getClassLoader().getResource("images/badge.png");
            if (badgeUrl == null) {
                throw new IOException("徽章图片未找到: images/badge.png");
            }
            ImageData badge = ImageDataFactory.create(badgeUrl);
            com.itextpdf.layout.element.Image badgeData = new com.itextpdf.layout.element.Image(badge);
            badgeData.scaleToFit(260, 260);
            mainPa.setTextAlignment(TextAlignment.CENTER);
            mainPa.add(badgeData);
            doc.add(mainPa);

            Paragraph sqsjParagraph = addParagraph(1.5f, 40, 58, 58);
            sqsjParagraph.add(addText("授权期限：" + request.getAuthorizationStart() + "至" + request.getAuthorizationEnd(), simsunFont, 18, 0, 0, TextAlignment.LEFT,1.5f));
            doc.add(sqsjParagraph);

            // 添加授权企业（companyP）和日期（datetimeP）到页面底部
            Paragraph companyP = addParagraph2(1.5f, 0, 50, 50); // 初始边距不再重要，会被固定位置覆盖
            companyP.add(addText("授权企业：" + request.getAuthorizationCompany(), alFont, 18, 0, 0, TextAlignment.RIGHT));
            // 设置固定位置：左侧50，距底部70点，宽度500
            companyP.setFixedPosition(50, 100, pageWidth-130);
            doc.add(companyP);

            Paragraph datetimeP = addParagraph2(1.5f, 0, 50, 50);
            datetimeP.add(addText(request.getSignDate(), alFont, 18, 0, 0, TextAlignment.RIGHT));
            // 设置在companyP下方，距底部50点
            datetimeP.setFixedPosition(50, 70, pageWidth - 160);
            doc.add(datetimeP);

            // 添加图像到companyP上方右侧
            URL sealUrl = CertificateService.class.getClassLoader().getResource("images/seal.png");
            if (sealUrl == null) {
                throw new IOException("印章图片未找到: images/seal.png");
            }
            ImageData imageData = ImageDataFactory.create(sealUrl);
            com.itextpdf.layout.element.Image image = new com.itextpdf.layout.element.Image(imageData);
            image.scaleToFit(122, 122); // 缩放图像尺寸

            // 设置图像位置：
            // - X坐标：右侧对齐（pageWidth - 图像宽度 - 右侧边距）
            // - Y坐标：高于 companyP 的顶部（120） + 间距（20）
            float imageX = pageWidth - 250; // 右侧边距50pt
            float imageY = 60; // 140（从页面底部向上的坐标）
            image.setFixedPosition(imageX, imageY);
            doc.add(image);
            doc.close();
            return baos.toByteArray();
        } catch (Exception e) {
            log.error("生成PDF失败", e);
            throw new IOException(e);
        } finally {
            baos.close();
        }
    }

    // 将 InputStream 转为字节数组
    private  byte[] toByteArray(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            return buffer.toByteArray();
        } finally {
            inputStream.close();
        }
    }

    public  Paragraph  addParagraph(  float leading, float marginTop, float marginLeft, float marginRight) {
        Paragraph paragraph = new Paragraph();
        paragraph.setMarginTop(marginTop);
        paragraph.setMarginLeft(marginLeft);
        paragraph.setMarginRight(marginRight);
        paragraph.setMultipliedLeading(leading);
        return paragraph;
    }
    public  Paragraph  addParagraph2(  float leading, float marginTop, float marginLeft, float marginRight) {
        Paragraph paragraph = new Paragraph();
        paragraph.setMarginTop(marginTop);
        paragraph.setMarginLeft(marginLeft);
        paragraph.setMarginRight(marginRight);
        paragraph.setTextAlignment(TextAlignment.RIGHT);
        paragraph.setMultipliedLeading(leading);
        return paragraph;
    }
    public  Paragraph  addParagraph3(  float leading, float bottom, float marginLeft, float marginRight) {
        Paragraph paragraph = new Paragraph();
        paragraph.setMarginBottom(bottom);
        paragraph.setMarginLeft(marginLeft);
        paragraph.setMarginRight(marginRight);
        paragraph.setTextAlignment(TextAlignment.RIGHT);
        paragraph.setMultipliedLeading(leading);
        return paragraph;
    }
    public Text addText(String text, PdfFont font, float fontSize,int isBold, int isUnderline,TextAlignment alignment){
        return addText(text, font, fontSize, isBold, isUnderline, alignment,2);
    }

    public Text addText(String text, PdfFont font, float fontSize, int isBold, int isUnderline, TextAlignment alignment, float characterSpacing) {
        Text txt = new Text(text).setFont(font).setFontSize(fontSize).setCharacterSpacing(characterSpacing);
        if (isBold == 1) {
            txt.simulateBold();
        }
        if (isUnderline == 1) {
            txt.setUnderline();
        }
        txt.setTextAlignment(alignment);
        return txt;
    }

}